package com.wsl.HealthChallenge.utils;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Provides some utility functions for redirecting.
 * @author mark
 */
public class Utils {
    /**
     * Forwards to the given relative URL. 
     * @param url
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public static void forwardToUrl(String url, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = request.getSession().getServletContext();
        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    /**
     * 
     * @param request
     * @param name
     * @return
     */
    public static String getParameter(HttpServletRequest request, String name) {
        String value = request.getParameter(name);
        if (value != null) {
            return value;
        }
        return "";
    }

    /**
     * Checks if the user is already logged in. if not it redirects to the
     * login URL and returns false. After the login is complete we will be redirected to exactly
     * where we came from. 
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public static boolean ensureUserLoggedIn(
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        if (userService.isUserLoggedIn()) {
            return true;
        } else {
            response.sendRedirect(userService.createLoginURL(Utils.getFullUrl(request)));
            return false;
        }
    }

    /**
     * @param request
     * @return the full URL inculding the query parameters.
     */
    public static String getFullUrl(HttpServletRequest request) {
        String fullUrl = request.getRequestURL().toString();
        String queryString = request.getQueryString();
        if (queryString != null && !queryString.isEmpty()) {
            fullUrl += "?" + queryString;
        }
        return fullUrl;
    }
}